package com.jason.rabbitmq;

import com.google.gson.Gson;
import com.jason.rabbitmq.entity.Order;
import com.jason.rabbitmq.util.OrderUtil;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class OrderController {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @RequestMapping("/add")
    public String add(@RequestBody Order order) {
        System.out.println("下订单:" + order);
        OrderUtil.addOrder(order);
        order.setStatus(Order.WAIT_PAY);
        order.setStatusDesc("待支付");
        Gson gson = new Gson();

        //发送消息
        rabbitTemplate.convertAndSend("ex.pay", "rout.pay", gson.toJson(order));
        return order.getId();
    }

    @RequestMapping("/orders")
    public List<Order> getOrders() {
        return OrderUtil.getAllOrder();
    }

    @RequestMapping("/pay")
    public String payOrder(String  orderId) {
        System.out.println(orderId + "订单支付成功");
        Order order = OrderUtil.getOrder(orderId);
        if (order.getStatus().intValue() == Order.OVERTIME.intValue()) {
            return "订单超时不能支付";
        } else {
            order.setStatus(Order.PAYED);
            order.setStatusDesc("已支付");
            return "支付成功";
        }
    }
}
